import React, { useState } from 'react';
import s from './style.module.css';
import {
  //   Table,
  Message,
  Button,
  Pagination,
  Confirm,
  Form,
  Input,
  Dialog,
  AntdTable,
  Loading,
} from '@knownsec/react-component';
import { Checkbox } from 'antd';

import cn from 'classnames';
// import { Table } from 'antd';
import { useHistory } from 'react-router-dom';
import recursionForm from '@/common/recursionForm';
import i from '../../../index.module.css';
import cookie from 'react-cookies';

import { warnAddUser, putWarnUser, delWarnUser, getWarnUserList } from '~/API';
export default function email() {
  const CusLoading = <Loading label="" />;
  const history = useHistory();
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const [refe] = useState(false);
  const [visible, setVisible] = useState(false); //添加告警人
  const [selTable, setSelTable] = useState([]);
  const [selRow, setSelRow] = useState({});
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [searchInfo, setSearchInfo] = useState({ page: 1, limit: 10 });
  const [loading, setLoading] = useState(false);
  const createForm = React.useRef();
  const columns = [
    {
      title: '告警联系人',
      dataIndex: 'contact_name',
    },
    // CM-944 隐藏发件邮箱字段
    // {
    //   title: '发件邮箱',
    //   dataIndex: 'sender',
    // },
    {
      title: '收件邮箱',
      dataIndex: 'receiver_email',
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (e, row) => {
        return (
          <>
            {row.receiver_type === 0 && cookie.load('username') !== 'admin' ? (
              <Button
                style={{ padding: 0, height: '24px', lineHeight: '24px' }}
                disabled
                type="text"
              >
                修改
              </Button>
            ) : (
              <span
                className={s.operation}
                onClick={() => {
                  showDialog(row);
                }}
              >
                修改
              </span>
            )}
            {row.receiver_type !== 0 && (
              <span
                className={s.operation}
                onClick={() => {
                  delDia([row.id]);
                }}
              >
                删除
              </span>
            )}
          </>
        );
      },
    },
  ];
  const getList = async (e) => {
    setLoading(true);
    const res = await getWarnUserList(e);
    let data = [];
    if (res.data.data) {
      data = res.data.data.map((e) => {
        e.id = e.receiver_id;
        e.key = e.receiver_id;
        return e;
      });
    }
    setLoading(false);
    setTableData({ data, total: res.data.total });
  };
  const delDia = (e) => {
    Confirm({
      pro: true,
      className: s.dialogName,
      title: '删除告警联系人',
      message: <div className={s.delBox}>确认删除选中的告警联系人？</div>,
      onconfirm: async () => {
        const params = {
          receiver_ids: e || selTable,
        };
        const res = await delWarnUser(params);
        if (res.status === 'success') {
          setSelTable([]);
          Message.show({
            pro: true,
            type: 'success',
            message: '删除成功',
            showClose: false,
          });
          onSearch({ page: 1, limit: 10 });
        }
      },
    });
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    createForm.current.setFieldsValue(values);
  };
  const submitInfo = async () => {
    const data = await createForm.current.validateFields();
    let res = null;
    if (!selRow) {
      res = await warnAddUser({ contact_name: data.fname, receiver_email: data.email }).catch(
        (err) => {
          return err;
        }
      );
    } else {
      res = await putWarnUser({
        receiver_id: selRow.receiver_id,
        data: { receiver_email: data.email },
      }).catch((err) => {
        return err;
      });
    }
    if (res.status === 'success') {
      setVisible('');
      onSearch({ page: 1, limit: 10 });
      Message.show({
        pro: true,
        type: 'success',
        message: '操作成功',
        showClose: false,
      });
    } else {
      let msg = '';
      if (res.message) {
        msg = res.message;
      } else {
        msg = Object.values(res.data)[0];
      }
      Message.show({
        pro: true,
        type: 'error',
        message: msg,
        showClose: false,
      });
    }
  };
  const showDialog = (row) => {
    if (row.receiver_type === 0) {
      history.push('/user_edit');
    } else {
      setSelRow(row);
      const t = row ? '修改联系人' : '添加联系人';
      setVisible(t);
      createForm.current.setFieldsValue({ fname: row.contact_name, email: row.receiver_email });
    }
  };
  const onSearch = (e) => {
    setSearchInfo({ page: e.page, limit: e.limit });
    let params = { page: e.page, limit: e.limit };
    getList(params);
  };
  const rowSelection = {
    selectedRowKeys: selTable,
    onChange: (selectedRowKeys) => {
      setSelTable(selectedRowKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.receiver_type === 0,
    }),
  };
  React.useMemo(() => {
    getList({ page: 1, limit: 10 });
  }, []);

  const [isChecked, setIsChecked] = useState(true);
  const handleCheckChange = () => {
    setIsChecked(!isChecked);
  };

  return (
    <div className={s.tableBox}>
      <div className={s.tool}>
        <Button
          pro
          type="primary"
          onClick={() => {
            showDialog(false);
          }}
        >
          添加联系人
        </Button>
      </div>
      <div>
        <Button
          pro
          type="text"
          className="delete-btn p0"
          disabled={!selTable.length}
          onClick={() => {
            delDia();
          }}
        >
          批量删除
        </Button>
      </div>
      <AntdTable
        rowSelection={{
          ...rowSelection,
        }}
        loading={loading ? { indicator: CusLoading } : false}
        columns={columns}
        dataSource={tableData.data}
        className={s.table}
        pagination={false}
      />
      {tableData.total > 10 && (
        <Pagination
          key={Number(123)}
          className={s.pagination}
          current={searchInfo.page}
          showQuickJumper={{ goButton: true }}
          showTotal={(total) => `共${total}条`}
          showSizeChanger={true}
          pageSize={searchInfo.limit}
          pageSizeOptions={['10', '20', '50']}
          total={tableData.total}
          onChange={(page, limit) => {
            onSearch({ page, limit });
          }}
        />
      )}
      <Dialog
        title={visible}
        visible={visible}
        confirmText=""
        cancelText=""
        className={s.w540}
        onhide={() => {
          setVisible(false);
          createForm.current.resetFields();
        }}
      >
        <div className={cn(i.p24)}>
          <Form
            ref={createForm}
            {...layout}
            onValuesChange={(newItem, allValues) => {
              onValues(newItem, allValues);
            }}
          >
            <Form.Item
              name="fname"
              label="告警联系人名称"
              rules={[{ required: true, message: '告警联系人名称不能为空' }]}
            >
              <Input
                pro
                autoComplete={'off'}
                disabled={selRow}
                className="flex1"
                maxlength={50}
                placeholder="请输入联系人名称"
              ></Input>
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '告警邮箱不能为空' }]}
              name="email"
              label="邮箱"
            >
              <Input
                pro
                autoComplete={'off'}
                className="flex1"
                maxlength={50}
                placeholder="请输入邮箱地址"
              ></Input>
            </Form.Item>
          </Form>
        </div>
        <div className={s.check}>
          <Checkbox onChange={handleCheckChange} />
          <div className={s.tips}>
            尊敬的用户，在您使用产品过程中，我们需要收集某些个人信息以提升服务质量。请您授权我们进行收集和使用，我们将严格遵守相关规定，确保您的信息安全。
          </div>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button
            className={i.vam}
            onClick={() => {
              createForm.current.resetFields();
              setVisible(false);
            }}
          >
            取消
          </Button>
          <Button
            disabled={isChecked}
            type="primary"
            className={cn(i.ml24, i.vam)}
            onClick={() => submitInfo()}
          >
            确定
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
